Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : src/app/maps/v1/[...path]/route.ts9 * Module : app10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2513 * Last Modified : 2026-11-2514 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */424344import { createHash } from "node:crypto";45import { open, readFile, realpath, stat } from "node:fs/promises";46import path from "node:path";47import { Readable } from "node:stream";48import { ApiError, clientIp } from "@/lib/security/http";49import { rateLimit } from "@/lib/security/ratelimit";5051export const dynamic = "force-dynamic";5253/**54 * ORIX Maps region packages (contract: docs/CATALOG_API.md of the ORIX Maps repository, section 2).55 *56 * GET|HEAD /maps/v1/catalog.json every region and its current version57 * GET|HEAD /maps/v1/regions/<id>.json one region in detail58 * GET|HEAD /maps/v1/regions/<id>/versions.json every published version of a region59 * GET|HEAD /maps/v1/files/<id>/<dataVersion>/<id>-<dataVersion>.orixmap the signed package, with Range support60 *61 * The distribution lives outside the deployment, in ORIX_MAPS_DIR (default ~/apps-data/orix-maps) + /v1, written by62 * `orix-package publish`. The URL is validated against the four shapes above before the file system is touched, and63 * the resolved file must stay under the distribution root (no traversal, no symbolic link leading outside). Anything64 * else, including the publisher's pins.json, answers 404.65 *66 * A package is served only when the current catalog.json or the region's versions.json lists it (path, size and67 * SHA-256) and its size on disk equals the listed size. Its ETag is the listed SHA-256: a package is never hashed68 * here. The JSON documents are hashed once per (mtime, size).69 *70 * Content-Length is set on every 200 and 206, but Next.js 16.4 strips it from route-handler responses (FORBIDDEN_HEADERS71 * in next/dist/server/send-response.js) and sends the body chunked: on the wire the size is known from the catalog and72 * from Content-Range only. See docs/development/map-distribution.md.73 *74 * Privacy: this route writes nothing: no log line, no counter, no file. The only state is the in-memory rate-limit75 * bucket of the caller's address (lib/security/ratelimit), which is never written to disk.76 */7778const ID = /^[a-z0-9-]{1,64}$/;79const VERSION = /^\d{1,10}(?:\.\d{1,10}){0,7}$/;80const SHA256 = /^[0-9a-f]{64}$/;81const MAX_DOCUMENT_BYTES = 8 * 1024 * 1024; // the client refuses a larger document82const RATE = { max: 300, windowSec: 60 }; // per address; a download costs one request per attempt or resume8384const JSON_CACHE = "public, max-age=300";85const ARTEFACT_CACHE = "public, max-age=31536000, immutable, no-transform";8687const root = () => path.join(process.env.ORIX_MAPS_DIR ?? path.join(process.env.HOME ?? "", "apps-data", "orix-maps"), "v1");8889const base = { "X-Content-Type-Options": "nosniff", "X-Robots-Tag": "noindex", "Access-Control-Allow-Origin": "*" };90const notFound = () => new Response("Not found", { status: 404, headers: { ...base, "Cache-Control": "no-store" } });9192/** The real path of a file of the distribution, or null when it does not exist or resolves outside the root. */93async function resolveInside(relative: string): Promise<string | null> {94 const realRoot = await realpath(root()).catch(() => null);95 if (!realRoot) return null;96 const joined = path.join(realRoot, relative);97 if (!joined.startsWith(realRoot + path.sep)) return null;98 const real = await realpath(joined).catch(() => null);99 return real && real.startsWith(realRoot + path.sep) ? real : null;100}101102type Document = { file: string; mtimeMs: number; size: number; raw: Buffer; etag: string; json: unknown };103const g = globalThis as typeof globalThis & { __orixMapDocuments?: Map<string, Document> };104105/** One JSON document of the distribution, with its SHA-256; read again only when its mtime or size changes. */106async function loadDocument(relative: string): Promise<Document | null> {107 const file = await resolveInside(relative);108 if (!file) return null;109 const st = await stat(/* turbopackIgnore: true */ file).catch(() => null);110 if (!st?.isFile() || st.size > MAX_DOCUMENT_BYTES) return null;111 const cache = (g.__orixMapDocuments ??= new Map());112 const hit = cache.get(relative);113 if (hit && hit.file === file && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit;114 const raw = await readFile(/* turbopackIgnore: true */ file);115 if (raw.length > MAX_DOCUMENT_BYTES) return null;116 let json: unknown = null;117 try { json = JSON.parse(raw.toString("utf8")); } catch { /* served as stored; it lists nothing */ }118 const loaded = { file, mtimeMs: st.mtimeMs, size: st.size, raw, etag: `"${createHash("sha256").update(raw).digest("hex")}"`, json };119 cache.set(relative, loaded);120 return loaded;121}122123type Listed = { size: number; sha256: string };124const record = (v: unknown): Record<string, unknown> | null => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null);125const array = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);126127/** What the published documents say about a package: catalog.json (current version) first, then the region's versions.json. */128async function listedArtefact(id: string, version: string, relative: string): Promise<Listed | null> {129 const candidates: unknown[] = [];130 const catalog = record((await loadDocument("catalog.json"))?.json);131 for (const r of array(catalog?.regions)) { const region = record(r); if (region?.id === id) candidates.push(region.latest); }132 const versions = record((await loadDocument(`regions/${id}/versions.json`))?.json);133 if (versions?.id === id) candidates.push(...array(versions.versions));134 for (const c of candidates) {135 const v = record(c);136 if (!v || v.path !== relative || v.dataVersion !== version) continue;137 if (typeof v.downloadSize !== "number" || !Number.isSafeInteger(v.downloadSize) || v.downloadSize < 0) continue;138 if (typeof v.sha256 !== "string" || !SHA256.test(v.sha256)) continue;139 return { size: v.downloadSize, sha256: v.sha256 };140 }141 return null;142}143144/** If-None-Match (RFC 9110 section 13.1.2): weak comparison against a list of tags, or `*`. */145function noneMatchHit(req: Request, etag: string): boolean {146 const header = req.headers.get("if-none-match");147 if (!header) return false;148 return header.split(",").map((t) => t.trim()).some((t) => t === "*" || t.replace(/^W\//, "") === etag);149}150151type Range = { start: number; end: number } | "unsatisfiable" | null;152153/**154 * One byte range (RFC 9110 section 14): `bytes=a-b`, `bytes=a-` and the suffix form `bytes=-n`. A Range header that is155 * malformed, in another unit or that asks for several ranges is ignored (section 14.2 lets a server ignore the header),156 * so the answer is 200 with the whole file. A well-formed range that starts at or after the end is unsatisfiable (416).157 */158function parseRange(header: string | null, size: number): Range {159 const m = /^bytes=(\d{0,16})-(\d{0,16})$/.exec(header?.trim() ?? "");160 if (!m || (!m[1] && !m[2])) return null;161 if (!m[1]) { // the last n bytes162 const n = Number(m[2]);163 return n === 0 || size === 0 ? "unsatisfiable" : { start: Math.max(0, size - n), end: size - 1 };164 }165 const start = Number(m[1]);166 if (m[2] && Number(m[2]) < start) return null; // not a valid range: ignored167 if (start >= size) return "unsatisfiable";168 return { start, end: m[2] ? Math.min(Number(m[2]), size - 1) : size - 1 };169}170171async function serveDocument(req: Request, relative: string, head: boolean): Promise<Response> {172 const doc = await loadDocument(relative);173 if (!doc) return notFound();174 if (noneMatchHit(req, doc.etag)) return new Response(null, { status: 304, headers: { ...base, ETag: doc.etag, "Cache-Control": JSON_CACHE } });175 return new Response(head ? null : new Uint8Array(doc.raw), {176 headers: { ...base, "Content-Type": "application/json", "Content-Length": String(doc.raw.length), ETag: doc.etag, "Cache-Control": JSON_CACHE },177 });178}179180async function serveArtefact(req: Request, id: string, version: string, head: boolean): Promise<Response> {181 const relative = `files/${id}/${version}/${id}-${version}.orixmap`;182 const listed = await listedArtefact(id, version, relative);183 if (!listed) return notFound();184 const file = await resolveInside(relative);185 if (!file) return notFound();186 const handle = await open(/* turbopackIgnore: true */ file, "r").catch(() => null);187 if (!handle) return notFound();188 let streaming = false;189 try {190 // The size is checked on the open descriptor: the bytes sent are those of the file that was measured.191 const st = await handle.stat();192 if (!st.isFile() || st.size !== listed.size) return notFound();193 const etag = `"${listed.sha256}"`;194 const headers: Record<string, string> = { ...base, "Content-Type": "application/vnd.orix.map", "Accept-Ranges": "bytes", ETag: etag, "Cache-Control": ARTEFACT_CACHE };195 if (noneMatchHit(req, etag)) return new Response(null, { status: 304, headers: { ...base, ETag: etag, "Cache-Control": ARTEFACT_CACHE } });196197 // Range applies to GET only (section 14.2). If-Range needs a strong match (section 13.1.5): with any other value,198 // including a weak tag or a date, the range is ignored and the whole file is sent.199 const ifRange = req.headers.get("if-range");200 const range = head || (ifRange !== null && ifRange.trim() !== etag) ? null : parseRange(req.headers.get("range"), st.size);201 if (range === "unsatisfiable") return new Response(null, { status: 416, headers: { ...base, "Accept-Ranges": "bytes", "Content-Range": `bytes */${st.size}`, "Cache-Control": "no-store" } });202 if (head) return new Response(null, { headers: { ...headers, "Content-Length": String(st.size) } });203 if (st.size === 0) return new Response(new Uint8Array(0), { headers: { ...headers, "Content-Length": "0" } });204205 const { start, end } = range ?? { start: 0, end: st.size - 1 };206 const body = Readable.toWeb(handle.createReadStream({ start, end, highWaterMark: 1024 * 1024 })) as ReadableStream; // closes the descriptor when done or cancelled207 streaming = true;208 if (range) return new Response(body, { status: 206, headers: { ...headers, "Content-Length": String(end - start + 1), "Content-Range": `bytes ${start}-${end}/${st.size}` } });209 return new Response(body, { headers: { ...headers, "Content-Length": String(st.size) } });210 } finally {211 if (!streaming) await handle.close().catch(() => undefined);212 }213}214215async function handle(req: Request, segments: string[], head: boolean): Promise<Response> {216 try { rateLimit("orix-maps", clientIp(req), RATE.max, RATE.windowSec); }217 catch (e) {218 const wait = e instanceof ApiError && typeof e.extra?.retryAfterSeconds === "number" ? e.extra.retryAfterSeconds : RATE.windowSec;219 return new Response("Too many requests", { status: 429, headers: { ...base, "Retry-After": String(Math.max(1, wait)), "Cache-Control": "no-store" } });220 }221 try {222 const [a, b, c, d] = segments;223 if (segments.length === 1 && a === "catalog.json") return await serveDocument(req, "catalog.json", head);224 if (segments.length === 2 && a === "regions" && b.endsWith(".json") && ID.test(b.slice(0, -5))) return await serveDocument(req, `regions/${b}`, head);225 if (segments.length === 3 && a === "regions" && ID.test(b) && c === "versions.json") return await serveDocument(req, `regions/${b}/versions.json`, head);226 if (segments.length === 4 && a === "files" && ID.test(b) && VERSION.test(c) && d === `${b}-${c}.orixmap`) return await serveArtefact(req, b, c, head);227 return notFound();228 } catch {229 // Deliberately silent: nothing about a request is logged from here.230 return new Response("Internal error", { status: 500, headers: { ...base, "Cache-Control": "no-store" } });231 }232}233234export async function GET(req: Request, { params }: { params: Promise<{ path: string[] }> }) { return handle(req, (await params).path, false); }235export async function HEAD(req: Request, { params }: { params: Promise<{ path: string[] }> }) { return handle(req, (await params).path, true); }236